﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CartoGraphic.MyTool;
using DocToolkit;
using CartoGraphic.Model;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
using CartoGraphic.Model2;

namespace CartoGraphic
{
    public partial class TestForm : Form
    {
        private DrawArea drawArea;
        private DocManager docManager;
        private DragDropManager dragDropManager;
        private DocManagerData data;
        private GraphicsProperties editGPS;

        public static Dictionary<string, string> symbolCode;  //编码索引
        public static Dictionary<string, string> infoCode;
        List<BaseDrawingObj> geos;
        DataFrame frame;
        IOBase iobase;
        Layers theLayers;
        Layer1 selectLayer;
        Addtibute.AttrTableDataTable table = new Addtibute.AttrTableDataTable();

        Point position; //显示提示的位置

        public TestForm()
        {
            InitializeComponent();
            InitializeHelperObjects();
            readCode();
            MouseWheel += new MouseEventHandler(MainForm_MouseWheel);
            drawArea = new DrawArea();
            drawArea.Initialize(this, docManager);
            drawArea.Dock = System.Windows.Forms.DockStyle.Fill;
            drawArea.Location = new Point(0, 0);
            drawArea.Size = new Size(10, 10);
            drawArea.BringToFront();
            //drawArea.ActiveTool = DrawArea.DrawToolType.Polygon;
            drawArea.MouseDown += new MouseEventHandler(普通模式ToolStripMenuItem_MouseDown);
            drawArea.MouseDown += new MouseEventHandler(TestForm_MouseDown);
            this.Controls.Add(drawArea);
            editGPS = new GraphicsProperties(Color.Red, Color.Brown, 4, true);
            drawArea.Graphic = this.CreateGraphics();
            ListViewItem listViewItem1 = new ListViewItem("植被", "1V_24.png");
            ListViewItem listViewItem2 = new ListViewItem("未知", "2C_24.png");
            ListViewItem listViewItem3 = new ListViewItem("图幅", "1C_24.png");
            ListViewItem listViewItem4 = new ListViewItem("水系", "1H_24.png");
            ListViewItem listViewItem5 = new ListViewItem("境界", "1F_24.png");
            ListViewItem listViewItem6 = new ListViewItem("建筑物", "1B_24.png");
            ListViewItem listViewItem7 = new ListViewItem("地貌", "1T_24.png");
            ListViewItem listViewItem8 = new ListViewItem("道路", "1R_24.png");
            layerControl.Items.Add(listViewItem3);
            layerControl.Items.Add(listViewItem6);
            layerControl.Items.Add(listViewItem8);
            layerControl.Items.Add(listViewItem5);
            layerControl.Items.Add(listViewItem4);
            layerControl.Items.Add(listViewItem7);
            layerControl.Items.Add(listViewItem1);
            layerControl.Items.Add(listViewItem2);
        }

        private void InitializeHelperObjects()
        {
            // DocManager
            data = new DocManagerData();
            data.FormOwner = this;
            data.UpdateTitle = true;
            data.FileDialogFilter = "DrawTools files (*.cg)|*.cg|All Files (*.*)|*.*";
            data.NewDocName = "未命名.cg";

            docManager = new DocManager(data);
            docManager.RegisterFileType("cg", "cgfile", "CartoGraphic File");

            docManager.NewDocument();
            dragDropManager = new DragDropManager(this);
            layerControl.AllowDrop = true;

        }

        private void TestForm_Resize(object sender, EventArgs e)
        {
            drawAll();
        }

        #region 预处理
        private void readCode()
        {
            try
            {
                symbolCode = new Dictionary<string, string>();
                infoCode = new Dictionary<string, string>();
                StreamReader sr = new StreamReader(@"code.csv", Encoding.GetEncoding("gb2312"));
                string sFile = sr.ReadToEnd();
                string[] vals = sFile.Split('\n');
                for (int i = 0; i < vals.Length; i++)
                {
                    string sLine = vals[i];
                    string[] sVal = sLine.Split(',');
                    if (sVal.Length < 3)
                        continue;
                    string key = sVal[0];
                    string value = sVal[2].Trim();
                    string value2 = sVal[3].Trim();
                    if (symbolCode.ContainsKey(key))
                        continue;
                    symbolCode.Add(key, value);
                    infoCode.Add(key, value2);
                }
                symbolCode.Add("32000", "B");
                infoCode.Add("32000", "B");
                symbolCode.Add("80000", "U");
                infoCode.Add("80000", "U");
                symbolCode.Add("Unknown", "U");
                infoCode.Add("Unknown", "U");
                symbolCode.Add("UnKnown", "U");
                infoCode.Add("UnKnown", "U");
                iobase = new IOBase();
                iobase.SymbolCode = symbolCode;
                iobase.InfoCode = infoCode;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

        }

        private void openFromRemote()
        {
            drawArea.TheLayers = new Model2.Layers();
            GraphicsProperties gps1 = new GraphicsProperties(Color.FromArgb(148, 148, 148), Color.FromArgb(189, 142, 140), 1, true);
            GraphicsProperties gps2 = new GraphicsProperties(Color.Black, Color.White, 2, true);
            GraphicsProperties gps3 = new GraphicsProperties(Color.FromArgb(75, 174, 219), Color.FromArgb(150, 247, 247), 1, true);
            GraphicsProperties gps4 = new GraphicsProperties(Color.Black, Color.White, 2, true);
            GraphicsProperties gps5 = new GraphicsProperties(Color.Black, Color.FromArgb(0, 0, 0, 0), 3, true);
            GraphicsProperties gps6 = new GraphicsProperties(Color.FromArgb(165, 118, 27), Color.FromArgb(0, 0, 0, 0), 1, true);
            GraphicsProperties gps7 = new GraphicsProperties(Color.FromArgb(133, 204, 118), Color.FromArgb(216, 255, 185), 1, true);
            GraphicsProperties gps8 = new GraphicsProperties(Color.Gray, Color.FromArgb(0, 0, 0, 0), 0, true);
            drawArea.TheLayers.CreateNewLayer("建筑物");
            drawArea.TheLayers.CreateNewLayer("道路");
            drawArea.TheLayers.CreateNewLayer("水系");
            drawArea.TheLayers.CreateNewLayer("图幅");
            drawArea.TheLayers.CreateNewLayer("境界");
            drawArea.TheLayers.CreateNewLayer("地貌");
            drawArea.TheLayers.CreateNewLayer("植被");
            drawArea.TheLayers.CreateNewLayer("未知");
            drawArea.TheLayers["建筑物"].GP = gps1;
            drawArea.TheLayers["道路"].GP = gps2;
            drawArea.TheLayers["水系"].GP = gps3;
            drawArea.TheLayers["图幅"].GP = gps4;
            drawArea.TheLayers["境界"].GP = gps5;
            drawArea.TheLayers["地貌"].GP = gps6;
            drawArea.TheLayers["植被"].GP = gps7;
            drawArea.TheLayers["未知"].GP = gps8;

            drawArea.TheLayers["建筑物"].Depth = 6;
            drawArea.TheLayers["道路"].Depth = 5;
            drawArea.TheLayers["水系"].Depth = 3;
            drawArea.TheLayers["图幅"].Depth = 7;
            drawArea.TheLayers["境界"].Depth = 4;
            drawArea.TheLayers["地貌"].Depth = 2;
            drawArea.TheLayers["植被"].Depth = 1;
            drawArea.TheLayers["未知"].Depth = 0;
            drawArea.TheLayers.InactivateAllLayers();
            theLayers = drawArea.TheLayers;
            layerControl.Items[0].Tag = theLayers["图幅"];
            layerControl.Items[1].Tag = theLayers["建筑物"];
            layerControl.Items[2].Tag = theLayers["道路"];
            layerControl.Items[3].Tag = theLayers["境界"];
            layerControl.Items[4].Tag = theLayers["水系"];
            layerControl.Items[5].Tag = theLayers["地貌"];
            layerControl.Items[6].Tag = theLayers["植被"];
            layerControl.Items[7].Tag = theLayers["未知"];

            frame = new DataFrame();
            geos = new List<BaseDrawingObj>();
            try
            {
                System.Net.WebClient client = new WebClient();
                client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                String url = Properties.Resources.url + "/data_for_client/";
                Stream data_remote = client.OpenRead(url);
                StreamReader reader = new StreamReader(data_remote);

                while (reader.Peek() > 0)
                {
                    string si = reader.ReadLine().Trim();
                    if (si.Equals("Point"))
                        geos.Add(iobase.openPoint(reader));
                    else if (si.Equals("PolyLine"))
                        geos.Add(iobase.openLine(reader));
                    else if (si.Equals("Polygon"))
                        geos.Add(iobase.openPolygon(reader));
                }
                data_remote.Close();
                reader.Close();
                frame.geos = geos;
                frame.trans();
                data.NewDocName ="远程";
                Layers layers = drawArea.TheLayers;
                foreach (BaseDrawingObj geo in geos)
                {

                    table.AddAttrTableRow(geo.ID.ToString(), geo.Code, geo.Info, geo.Type, geo.Dimension);
                    string type = geo.Type;
                    if (type.Equals("B"))
                        layers["建筑物"].Graphics.Add(geo);
                    else if (type.Equals("C"))
                        layers["图幅"].Graphics.Add(geo);
                    else if (type.Equals("F"))
                        layers["境界"].Graphics.Add(geo);
                    else if (type.Equals("H"))
                        layers["水系"].Graphics.Add(geo);
                    else if (type.Equals("R"))
                        layers["道路"].Graphics.Add(geo);
                    else if (type.Equals("T"))
                        layers["地貌"].Graphics.Add(geo);
                    else if (type.Equals("V"))
                        layers["植被"].Graphics.Add(geo);
                    else if (type.Equals("U"))
                        layers["未知"].Graphics.Add(geo);
                }
                drawArea.PanX = 0;
                drawArea.PanY = 0;
                drawAll();
                drawArea.Panning = true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void openDoc()
        {
            drawArea.TheLayers = new Model2.Layers();
            GraphicsProperties gps1 = new GraphicsProperties(Color.FromArgb(148, 148, 148), Color.FromArgb(189, 142, 140), 1, true);
            GraphicsProperties gps2 = new GraphicsProperties(Color.Black, Color.White, 2, true);
            GraphicsProperties gps3 = new GraphicsProperties(Color.FromArgb(75, 174, 219), Color.FromArgb(150, 247, 247), 1, true);
            GraphicsProperties gps4 = new GraphicsProperties(Color.Black, Color.White, 2, true);
            GraphicsProperties gps5 = new GraphicsProperties(Color.Black, Color.FromArgb(0, 0, 0, 0), 3, true);
            GraphicsProperties gps6 = new GraphicsProperties(Color.FromArgb(165, 118, 27), Color.FromArgb(0, 0, 0, 0), 1, true);
            GraphicsProperties gps7 = new GraphicsProperties(Color.FromArgb(133, 204, 118), Color.FromArgb(216, 255, 185), 1, true);
            GraphicsProperties gps8 = new GraphicsProperties(Color.Gray, Color.FromArgb(0, 0, 0, 0), 0, true);
            drawArea.TheLayers.CreateNewLayer("建筑物");
            drawArea.TheLayers.CreateNewLayer("道路");
            drawArea.TheLayers.CreateNewLayer("水系");
            drawArea.TheLayers.CreateNewLayer("图幅");
            drawArea.TheLayers.CreateNewLayer("境界");
            drawArea.TheLayers.CreateNewLayer("地貌");
            drawArea.TheLayers.CreateNewLayer("植被");
            drawArea.TheLayers.CreateNewLayer("未知");
            drawArea.TheLayers["建筑物"].GP = gps1;
            drawArea.TheLayers["道路"].GP = gps2;
            drawArea.TheLayers["水系"].GP = gps3;
            drawArea.TheLayers["图幅"].GP = gps4;
            drawArea.TheLayers["境界"].GP = gps5;
            drawArea.TheLayers["地貌"].GP = gps6;
            drawArea.TheLayers["植被"].GP = gps7;
            drawArea.TheLayers["未知"].GP = gps8;

            drawArea.TheLayers["建筑物"].Depth = 6;
            drawArea.TheLayers["道路"].Depth = 5;
            drawArea.TheLayers["水系"].Depth = 3;
            drawArea.TheLayers["图幅"].Depth = 7;
            drawArea.TheLayers["境界"].Depth = 4;
            drawArea.TheLayers["地貌"].Depth = 2;
            drawArea.TheLayers["植被"].Depth = 1;
            drawArea.TheLayers["未知"].Depth = 0;
            drawArea.TheLayers.InactivateAllLayers();
            theLayers = drawArea.TheLayers;
            layerControl.Items[0].Tag = theLayers["图幅"];
            layerControl.Items[1].Tag = theLayers["建筑物"];
            layerControl.Items[2].Tag = theLayers["道路"];
            layerControl.Items[3].Tag = theLayers["境界"];
            layerControl.Items[4].Tag = theLayers["水系"];
            layerControl.Items[5].Tag = theLayers["地貌"];
            layerControl.Items[6].Tag = theLayers["植被"];
            layerControl.Items[7].Tag = theLayers["未知"];

            frame = new DataFrame();
            geos = new List<BaseDrawingObj>();
            OpenFileDialog dlg = new OpenFileDialog();
            //dlg.ShowDialog();
            dlg.Filter = "Text Files(*.txt;*.cg;)|*.txt;*.cg;|All files(*.*)|*.* ";
            dlg.Title = "打开文件";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                FileInfo fi = new FileInfo(dlg.FileName);
                Rectangle rect = ClientRectangle;
                frame.g = CreateGraphics();
                drawArea.Graphic = frame.g;
                frame.screenHeight = ClientRectangle.Height;
                frame.screenWidth = ClientRectangle.Width;
                if (dlg.FileName.EndsWith(".cg"))
                {
                    StreamReader sr1 = fi.OpenText();
                    while (sr1.Peek() > 0)
                    {
                        string si = sr1.ReadLine().Trim();
                        if (si.Equals("Point"))
                            geos.Add(iobase.openPoint(sr1));
                        else if (si.Equals("PolyLine"))
                            geos.Add(iobase.openLine(sr1));
                        else if (si.Equals("Polygon"))
                            geos.Add(iobase.openPolygon(sr1));
                    }
                }
                else if (dlg.FileName.EndsWith(".txt"))
                {
                    StreamReader sr = fi.OpenText();
                    string s = sr.ReadLine();   //第一行读取上下左右边界
                    string[] fls = s.Split(',');
                    frame.left = Double.Parse(fls[0]);
                    frame.down = Double.Parse(fls[1]);
                    frame.right = Double.Parse(fls[2]);
                    frame.up = Double.Parse(fls[3]);
                    sr.ReadLine();
                    sr.ReadLine();
                    while (sr.Peek() > 0)
                    {
                        s = sr.ReadLine();
                        if (!s.Contains(" "))
                            continue;
                        string type = s.Split(' ')[0].Trim();
                        int count = Int16.Parse(s.Split(' ')[1].Trim());
                        if (count == 0)
                            continue;
                        if (type.Equals("Point"))
                        {
                            List<SimplePoint> points = readPoint(sr, count);
                            geos.AddRange(points);
                        }
                        else if (type.Equals("Polyline"))
                        {
                            List<PolyLine> lines = readLines(sr, count);
                            geos.AddRange(lines);
                        }
                        else if (type.Equals("Polygon"))
                        {
                            List<Polygon> polygons = readPolygon(sr, count);
                            geos.AddRange(polygons);
                        }
                    }
                    sr.Close();
                    frame.geos = geos;
                    frame.trans();
                }
                data.NewDocName = dlg.FileName;
                Layers layers = drawArea.TheLayers;
                foreach (BaseDrawingObj geo in geos)
                {

                    table.AddAttrTableRow(geo.ID.ToString(), geo.Code, geo.Info, geo.Type, geo.Dimension);
                    string type = geo.Type;
                    if (type.Equals("B"))
                        layers["建筑物"].Graphics.Add(geo);
                    else if (type.Equals("C"))
                        layers["图幅"].Graphics.Add(geo);
                    else if (type.Equals("F"))
                        layers["境界"].Graphics.Add(geo);
                    else if (type.Equals("H"))
                        layers["水系"].Graphics.Add(geo);
                    else if (type.Equals("R"))
                        layers["道路"].Graphics.Add(geo);
                    else if (type.Equals("T"))
                        layers["地貌"].Graphics.Add(geo);
                    else if (type.Equals("V"))
                        layers["植被"].Graphics.Add(geo);
                    else if (type.Equals("U"))
                        layers["未知"].Graphics.Add(geo);
                }
                drawArea.PanX = 0;
                drawArea.PanY = 0;
                drawAll();
                drawArea.Panning = true;
            }
        }

        private List<SimplePoint> readPoint(StreamReader sr, int pointCount)
        {
            List<SimplePoint> points = new List<SimplePoint>();
            //List<PointGeo> points = new List<PointGeo>();
            string s = "", codeInfo = "";
            double x, y;
            for (int i = 0; i < pointCount * 2; i++)
            {
                s = sr.ReadLine();
                if (i % 2 == 0)
                {
                    codeInfo = s.Trim();
                }
                if (i % 2 == 1)
                {
                    string[] locations = s.Split(',');
                    x = Double.Parse(locations[0]);
                    y = Double.Parse(locations[1]);
                    SimplePoint geo = new SimplePoint(frame.transPoint(x, y), infoCode[codeInfo]);
                    geo.Code = codeInfo;
                    geo.Type = symbolCode[codeInfo];
                    geo.Dimension = "点";
                    //SimplePoint geo = new PointGeo(new MyPoint(x, y), symbolCode[codeInfo]);
                    geo.Info = infoCode[codeInfo];
                    points.Add(geo);
                }
            }
            return points;
        }

        private List<PolyLine> readLines(StreamReader sr, int lineCount)
        {
            List<PolyLine> lines = new List<PolyLine>();
            string s = "";
            for (int i = 0; i < lineCount; i++)
            {
                PolyLine line = new PolyLine();
                //List<MyPoint> linepoints = new List<MyPoint>();
                s = sr.ReadLine();
                string codeinfo = s.Trim();
                s = sr.ReadLine();
                int pointCount = Int16.Parse(s.Trim());
                for (int j = 0; j < pointCount; j++)
                {
                    s = sr.ReadLine();
                    double x = Double.Parse(s.Split(',')[0].Trim());
                    double y = Double.Parse(s.Split(',')[1].Trim());
                    line.AddPoint(frame.transPoint(x, y));
                    //linepoints.Add(new MyPoint(x, y));
                }
                line.Code = codeinfo;
                line.Info = infoCode[codeinfo];
                //PolyLineGeo line = new PolyLineGeo(linepoints);
                line.Type = symbolCode[codeinfo];
                //line.info = infoCode[codeinfo];
                line.Dimension = "线";
                lines.Add(line);
                sr.ReadLine();
            }
            return lines;
        }

        private List<Polygon> readPolygon(StreamReader sr, int polygonCount)
        {
            List<Polygon> lines = new List<Polygon>();
            string s = "";
            for (int i = 0; i < polygonCount; i++)
            {
                Polygon polygon = new Polygon();
                //List<MyPoint> linepoints = new List<MyPoint>();
                s = sr.ReadLine();
                string codeinfo = s.Trim();
                s = sr.ReadLine();
                int pointCount = Int16.Parse(s.Trim());
                for (int j = 0; j < pointCount; j++)
                {
                    s = sr.ReadLine();
                    double x = Double.Parse(s.Split(',')[0].Trim());
                    double y = Double.Parse(s.Split(',')[1].Trim());
                    polygon.AddPoint(frame.transPoint(x, y));
                    //linepoints.Add(new MyPoint(x, y));
                }
                //PolygonGeo line = new PolygonGeo(linepoints);
                polygon.Info = infoCode[codeinfo];
                polygon.Code = codeinfo;
                polygon.Type = symbolCode[codeinfo];
                polygon.Dimension = "面";
                //line.info = infoCode[codeinfo];
                lines.Add(polygon);
                sr.ReadLine();
            }
            return lines;
        }
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {


        }

        private void MainForm_MouseWheel(object sender, MouseEventArgs e)
        {
            if (e.Delta != 0)
            {
                if (e.Delta > 0)
                    AdjustZoom(.1f);
                else
                    AdjustZoom(-.1f);
                tip.Show("Scale:" + String.Format("{0:F2}", drawArea.Zoom), this, new Point(e.X, e.Y));
                return;
            }
        }

        private void AdjustZoom(float _amount)
        {
            drawArea.Zoom += _amount;
            if (drawArea.Zoom < .1f)
                drawArea.Zoom = .1f;
            if (drawArea.Zoom > 10)
                drawArea.Zoom = 10f;
            drawArea.Invalidate();

        }

        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void drawAll()
        {
            if (geos == null)
                return;
            if (geos.Count == 0)
                return;
            drawArea.TheLayers.Draw(frame.g);
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {


        }

        private void 打开ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            openFromRemote();
            //openDoc();
            drawArea.TheLayers.Draw(frame.g);
        }

        private void 编辑模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectLayer == null)
            {
                MessageBox.Show("请先选择图层！");
                return;
            }
            toolStripStatusLabel1.Text = "编辑模式";
            //drawArea.TheLayers.SetActiveLayer("建筑物");
            drawArea.Panning = false;
            drawArea.ActiveTool = DrawArea.DrawToolType.Pointer;
            drawAll();
        }

        private void 普通模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = "普通模式";
            drawArea.Panning = true;
            //drawArea.TheLayers[drawArea.TheLayers.ActiveLayerIndex].GP = new GraphicsProperties(Color.Black, Color.Black, 4, false);
            drawArea.TheLayers.InactivateAllLayers();
            drawAll();
        }

        private void 绘制模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //toolStripStatusLabel1.Text = "普通模式";
            //drawArea.ActiveTool = DrawArea.DrawToolType.Polygon;
        }

        private void 画点ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectLayer == null)
            {
                MessageBox.Show("请先选择图层！");
                return;
            }
            toolStripStatusLabel1.Text = "画点模式";
            drawArea.Panning = false;
            drawArea.ActiveTool = DrawArea.DrawToolType.Point;

            //drawArea.TheLayers[selectLayer.LayerName].GP = editGPS;
            drawArea.TheLayers.SetActiveLayer(selectLayer.LayerName);
        }

        private void 画线ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectLayer == null)
            {
                MessageBox.Show("请先选择图层！");
                return;
            }
            toolStripStatusLabel1.Text = "画线模式";
            drawArea.Panning = false;
            drawArea.ActiveTool = DrawArea.DrawToolType.PolyLine;
            //drawArea.TheLayers[selectLayer.LayerName].GP = editGPS;
            drawArea.TheLayers.SetActiveLayer(selectLayer.LayerName);
        }

        private void 画面ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectLayer == null)
            {
                MessageBox.Show("请先选择图层！");
                return;
            }
            toolStripStatusLabel1.Text = "画面模式";
            drawArea.Panning = false;
            drawArea.ActiveTool = DrawArea.DrawToolType.Polygon;
            //drawArea.TheLayers[selectLayer.LayerName].GP = editGPS;
            drawArea.TheLayers.SetActiveLayer(selectLayer.LayerName);
        }

        private void layerControl_MouseLeave(object sender, EventArgs e)
        {
            if (layerContextMenu.Visible == true)
                return;
            button1.Visible = true;
            button2.Visible = true;
            layerControl.Visible = false;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            if (theLayers == null)
                return;
            layerControl.Visible = true;
            button1.Visible = false;
            button2.Visible = false;
        }

        private void layerControl_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = e.AllowedEffect;
        }

        private void layerControl_DragDrop(object sender, DragEventArgs e)
        {
            ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
            //listView1.Items.Add((ListViewItem)item.Clone());
            Point Position = new Point(e.X, e.Y);
            Position = layerControl.PointToClient(Position);
            ListViewItem DropNode = this.layerControl.GetItemAt(Position.X, Position.Y);
            layerControl.Items.Insert(DropNode.Index, (ListViewItem)item.Clone());
            (DropNode.Tag as Layer1).Depth = DropNode.Index;
            (item.Tag as Layer1).Depth = item.Index;
            layerControl.Items.Remove(item);
            drawAll();
        }

        private void layerControl_ItemDrag(object sender, ItemDragEventArgs e)
        {
            layerControl.DoDragDrop(e.Item, DragDropEffects.Move);
        }

        private void layerControl_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                layerContextMenu.Show(layerControl, new Point(e.X, e.Y));
            }
        }

        private void layerControl_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void toolStripMenuItemSelect_Click(object sender, EventArgs e)
        {
            if (layerControl.SelectedItems.Count < 1)
                return;
            ListViewItem item = layerControl.SelectedItems[0];
            selectLayer = item.Tag as Layer1;
            theLayers.SetActiveLayer(selectLayer.LayerName);
            locationStatus.Text = "激活图层：" + selectLayer.LayerName;
            //MessageBox.Show("选中的是" + selectLayer.LayerName);
        }

        private void toolStripMenuItemVisible_Click(object sender, EventArgs e)
        {
            if (layerControl.SelectedItems.Count < 1)
                return;
            ListViewItem item = layerControl.SelectedItems[0];
            selectLayer = item.Tag as Layer1;
            if (selectLayer.IsVisible == true)
            {
                selectLayer.IsVisible = false;
                item.ForeColor = Color.Gray;
            }

            else
            {
                selectLayer.IsVisible = true;
                item.ForeColor = Color.Black;
            }
            drawAll();
        }

        private void toolStripMenuItemMoveUp_Click(object sender, EventArgs e)
        {
            ListViewItem selectNode = layerControl.SelectedItems[0];
            List<ListViewItem> items = new List<ListViewItem>();
            if (selectNode.Index == 0)
            {
                MessageBox.Show("当前图层不能上移！");
                return;
            }
            var selectLayer = selectNode.Tag as Layer1;
            var preLayer = layerControl.Items[selectNode.Index - 1].Tag as Layer1;
            selectLayer.Depth++;
            preLayer.Depth--;
            layerControl.Items.Insert(selectNode.Index - 1, (ListViewItem)selectNode.Clone());
            layerControl.Items.Remove(selectNode);
            for (int i = 0; i < layerControl.Items.Count; i++)
                items.Add((ListViewItem)layerControl.Items[i].Clone());
            layerControl.Items.Clear();
            foreach (ListViewItem item in items)
                layerControl.Items.Add(item);
            layerControl.Refresh();
            drawAll();
        }

        private void toolStripMenuItemMoveDown_Click(object sender, EventArgs e)
        {
            ListViewItem selectNode = layerControl.SelectedItems[0];
            List<ListViewItem> items = new List<ListViewItem>();
            if (selectNode.Index == layerControl.Items.Count - 1)
            {
                MessageBox.Show("当前图层不能下移！");
                return;
            }
            var selectLayer = selectNode.Tag as Layer1;
            var preLayer = layerControl.Items[selectNode.Index + 1].Tag as Layer1;
            selectLayer.Depth--;
            preLayer.Depth++;
            for (int i = 0; i < layerControl.Items.Count; i++)
                items.Add((ListViewItem)layerControl.Items[i].Clone());
            items.Insert(selectNode.Index + 2, (ListViewItem)selectNode.Clone());
            items.RemoveAt(selectNode.Index);
            //layerControl.Items.Remove(selectNode);
            layerControl.Items.Clear();
            //for (int i = 0; i < layerControl.Items.Count; i++)
            //    items.Add((ListViewItem)layerControl.Items[i].Clone());

            foreach (ListViewItem item in items)
                layerControl.Items.Add(item);
            layerControl.Refresh();
            drawAll();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            dataGridView1.Visible = true;
            dataGridView1.DataSource = table;
            button1.Visible = false;
            button2.Visible = false;
        }

        private void dataGridView1_MouseLeave(object sender, EventArgs e)
        {
            if (arrtibuteContextMenu.Visible == true)
                return;
            button1.Visible = true;
            button2.Visible = true;
            dataGridView1.Visible = false;
        }

        private void sparkmenuitem_Click(object sender, EventArgs e)
        {

            for (int i = dataGridView1.SelectedRows.Count - 1; i >= 0; i--)
            {
                DataRow row = (dataGridView1.SelectedRows[i].DataBoundItem as DataRowView).Row;
                long index = long.Parse(row[0].ToString());
                foreach (BaseDrawingObj geo in geos)
                    if (index == geo.ID)
                    {
                        drawArea.Spark(geo);
                    }
            }
        }

        //筛选
        private void scaleMenuItem1_Click(object sender, EventArgs e)
        {
            Selector form = new Selector();
            form.ShowDialog();
            DataRow[] rows = table.Select(form.Search);
            dataGridView1.DataSource = rows;
            MessageBox.Show("一共筛选出" + rows.Length + "个实体.");
        }

        private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && dataGridView1.SelectedRows.Count > 0)
            {
                arrtibuteContextMenu.Show(dataGridView1, new Point(e.X, e.Y));
            }
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "CartoGraphic Files(*.cg)|*.cg|Figure Files(*.bmp)|*.bmp|All files(*.*)|*.* ";
            dlg.Title = "保存文件";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (dlg.FileName.EndsWith(".bmp"))
                {
                    Bitmap bitmap = new Bitmap(1000, 800);
                    Graphics newGraphics = Graphics.FromImage(bitmap);
                    theLayers.Draw(newGraphics);
                    bitmap.Save(dlg.FileName);
                    newGraphics.Dispose();
                }
                FileInfo fi = new FileInfo(dlg.FileName);
                FileStream file = fi.OpenWrite();
                StreamWriter wr = new StreamWriter(file);
                foreach (KeyValuePair<string, Layer1> pair in theLayers.layerlist)
                {
                    Layer1 thelayer = pair.Value;
                    if (thelayer.IsVisible == true)
                    {
                        for (int i = 0; i < thelayer.Graphics.Count; i++)
                        {
                            BaseDrawingObj obj = thelayer.Graphics[i];
                            if (obj.GetType() == typeof(SimplePoint))
                            {
                                IOBase.writePoint(wr, (SimplePoint)obj);
                            }
                            if (obj.GetType() == typeof(PolyLine))
                            {
                                IOBase.writePolyLine(wr, (PolyLine)obj);
                            }
                            if (obj.GetType() == typeof(Polygon))
                            {
                                IOBase.writePolygon(wr, (Polygon)obj);
                            }
                        }
                    }
                }
                wr.Close();
            }
        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {

        }


        private void toolStripMenuItemArrt_Click(object sender, EventArgs e)
        {
            try
            {
                string tipstring = drawArea.SelectAttribute;
                if (tipstring == null)
                {
                    MessageBox.Show("没有选中任何实体！");
                    return;
                }
                tip.Show(drawArea.SelectAttribute, this, position);
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }

        }

        private void toolStripMenuItemdelete_Click(object sender, EventArgs e)
        {
            drawArea.deleteSelectObj();
        }

        private void 普通模式ToolStripMenuItem_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                position = new Point(e.X, e.Y);
                drawAreaContextMenu.Show(this, e.X, e.Y);
            }
        }

        private void TestForm_MouseDown(object sender, MouseEventArgs e)
        {
            tip.Hide(this);
        }

        private void 属性ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (layerControl.SelectedItems.Count < 1)
                return;
            ListViewItem item = layerControl.SelectedItems[0];
            selectLayer = item.Tag as Layer1;
            StyleForm form = new StyleForm();
            form.BorderColor = selectLayer.GP.BorderColor;
            form.FillColor = selectLayer.GP.FillColor;
            form.PenWidth = selectLayer.GP.PenWidth;
            form.ShowDialog();
            GraphicsProperties gp = new GraphicsProperties(form.BorderColor, form.FillColor, form.PenWidth, form.IsFill);
            selectLayer.GP = gp;
            drawArea.Refresh();
        }

        private void 导出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "CSV Files(*.csv)|*.csv|All files(*.*)|*.* ";
            dlg.Title = "保存文件";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                IOBase.ExportToCSV(table, dlg.FileName);
            }

        }

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;
            BaseDrawingObj select = null;
            long oid = Int64.Parse(table.Rows[e.RowIndex][0].ToString());
            foreach (BaseDrawingObj obj in geos)
                if (obj.ID == oid)
                {
                    select = obj;
                    return;
                }
            select.Code = table.Rows[e.RowIndex][1].ToString();
            select.Info = table.Rows[e.RowIndex][2].ToString();
            select.Type = table.Rows[e.RowIndex][3].ToString();
        }

        private void 地图综合ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<SimplePoint> samplePoints = new List<SimplePoint>();
            List<PolyLine> sampleLines = new List<PolyLine>();
            List<Polygon> samplePolygons = new List<Polygon>();

            foreach (BaseDrawingObj obj in geos)
                if (obj.Dimension == "点")
                    samplePoints.Add((SimplePoint)obj);
            Layer1 lineLayer = theLayers["地貌"];
            for (int i = 0; i < lineLayer.Graphics.Count; i++)
                if (lineLayer.Graphics[i].Dimension == "线")
                    sampleLines.Add((PolyLine)lineLayer.Graphics[i]);
            Layer1 polygonLayer = theLayers["建筑物"];
            for (int i = 0; i < polygonLayer.Graphics.Count; i++)
                if (polygonLayer.Graphics[i].Dimension == "面" && polygonLayer.Graphics[i].Code == "32029")
                    samplePolygons.Add((Polygon)polygonLayer.Graphics[i]);
            int xmin = 0, ymin = 0, xmax = 0, ymax = 0;
            foreach (Polygon geo in samplePolygons)
            {
                int count = geo.PointArray.Count;
                for (int i = 0; i < count; i++)
                {
                    Point point = (Point)geo.PointArray[i];
                    if (point.X < xmin)
                        xmin = point.X;
                    if (point.X > xmax)
                        xmax = point.X;
                }
            }
            SimplifyForm form = new SimplifyForm();
            form.line1 = sampleLines;
            form.pointsS = samplePoints;
            form.polygons = samplePolygons;
            form.Show();
        }

        private void 空间索引ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new Util.QuadTreeForm().Show();
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //DataRow row = (dataGridView1.SelectedRows[0].DataBoundItem as DataRowView).Row;
            List<long> indexs = new List<long>();
            for (int i = dataGridView1.SelectedRows.Count - 1; i >= 0; i--)
            {
                DataRow row = (dataGridView1.SelectedRows[i].DataBoundItem as DataRowView).Row;
                indexs.Add(long.Parse(row[0].ToString()));
                table.Rows.Remove(row);
            }

            foreach (KeyValuePair<string, Layer1> pair in theLayers.layerlist)
            {
                int count = pair.Value.Graphics.Count;
                for (int i = count - 1; i >= 0; i--)
                {
                    if (indexs.Contains(pair.Value.Graphics[i].ID))
                        pair.Value.Graphics.RemoveAt(i);
                }
            }
            MessageBox.Show("一共删除了" + indexs.Count + "个实体！");
        }

        private void 全部可见ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (KeyValuePair<string, Layer1> pair in theLayers.layerlist)
            {
                pair.Value.IsVisible = true;
            }
        }

        private void 全部不可见ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (KeyValuePair<string, Layer1> pair in theLayers.layerlist)
            {
                pair.Value.IsVisible = false;
            }
        }
    }
}
